from django.contrib import admin
from .models import Category, Image, Rating
from django.db import models

class ImageAdmin(admin.ModelAdmin):
    list_display = ('name', 'category', 'get_average_rating', 'get_all_user_ratings')

    # 获取每张图片的平均评分
    def get_average_rating(self, obj):
        ratings = obj.ratings.all()
        if ratings:
            average_rating = ratings.aggregate(models.Avg('rating_id'))['rating_id__avg']
            return round(average_rating, 2) if average_rating else '暂无评分'
        return '暂无评分'
    get_average_rating.short_description = '平均评分'

    # 获取所有用户评分
    def get_all_user_ratings(self, obj):
        ratings = obj.ratings.all()
        return ", ".join([f"{rating.user.username}: {rating.rating_id}" for rating in ratings]) if ratings else '暂无评分'
    get_all_user_ratings.short_description = '所有用户评分'

# 注册模型和管理员
admin.site.register(Category)
admin.site.register(Image, ImageAdmin)
admin.site.register(Rating)
